package com.qqtech.qquan.coupon.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.coupon.enums.CouponUserObtainWayDictEnum;
import com.qqtech.qquan.coupon.enums.CouponUserStatusDictEnum;
import com.qqtech.qquan.coupon.model.CouponBase;
import com.qqtech.qquan.coupon.model.CouponBaseVo;
import com.qqtech.qquan.coupon.model.CouponUser;
import com.qqtech.qquan.coupon.model.CouponUserQuery;
import com.qqtech.qquan.coupon.model.CouponUserVo;
import com.qqtech.qquan.coupon.service.CouponBaseService;
import com.qqtech.qquan.coupon.service.CouponUserService;
import com.qqtech.qquan.push.service.PushBizzService;
import com.qqtech.qquan.sys.controller.BaseAdminController;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.sys.model.SysParam;
import com.qqtech.qquan.sys.service.SysParamService;
import com.qqtech.qquan.util.ExcelUtil;

@Controller
@RequestMapping(value = "/coupon/user")
public class CouponUserController extends BaseAdminController {
	@Resource
	private CouponUserService couponUserService;

	@Resource
	private CouponBaseService couponBaseService;
	@Resource
	private SysParamService sysParamService;
	@Resource
	private PushBizzService pushBizzService;

	@Override
	protected BaseService<CouponUser> getBaseService() {
		return couponUserService;
	}

	/**
	 * 查询优惠券的用户
	 * 
	 * @param couponId
	 * @return
	 */
	@RequestMapping(value = "/list/{couponId}", method = RequestMethod.GET)
	public String list(@PathVariable Integer couponId) {
		return "/coupon/user-list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(CouponUserQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(), new PageOrder(Direction.DESC, "id"));
		Page<CouponUserVo> page = couponUserService.queryPageListAdmin(query, pageKit);
		if (page.getContent() != null) {
			Timestamp now = TimeUtil.now();
			for (CouponUserVo temp : page.getContent()) {
				if (temp.getExpireAt() != null && temp.getExpireAt().before(now)) {
					temp.setStrStatus("已过期");
					temp.setUpdAt(null);
				} else if (temp.getStatus().intValue() == CouponUserStatusDictEnum.NOT_USED.getCode()) {
					temp.setStrStatus("未使用");
					temp.setUpdAt(null);
				} else if (temp.getStatus().intValue() == CouponUserStatusDictEnum.BE_USED.getCode()) {
					temp.setStrStatus("已使用");
				} else {
					temp.setStrStatus("已过期");
					temp.setUpdAt(null);
				}
			}
		}
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	@RequestMapping(value = "/addUser")
	@ResponseBody
	public Result addUser(CouponUserVo entity) {
		Result ret = new Result();
		if (entity == null) {
			ret.addErr("数据不能为空");
		} else {
			CouponBase base = couponBaseService.getById(entity.getCouponId());
			if (base == null) {
				ret.addErr("不存在优惠券");
			} else if (base.getStatus().intValue() == 2) {
				ret.addErr("该优惠券已停用");
			}
			if (StringUtil.isBlank(entity.getUserIds())) {
				ret.addErr("请选择用户");
			}
		}
		if (ret.checkForm()) {
			String[] temp = entity.getUserIds().split(",");
			List<Integer> userIds = new ArrayList<Integer>(temp.length);
			for (int i = 0; i < temp.length; i++) {
				userIds.add(Integer.valueOf(temp[i]));
			}
			couponUserService.addCouponUserBatch(userIds, entity.getCouponId(), CouponUserObtainWayDictEnum.ADMIN,
					null);
			// 增加推送信息
			String msg = "天下真掉馅饼了,一波优惠卷向你砸来";
			if (StringUtil.isNotBlank(entity.getPushMsg())) {
				msg = entity.getPushMsg();
			} else {
				CouponBaseVo couponBaseVo = couponBaseService.getById(entity.getCouponId());
				msg = "这天真掉馅饼了,一波优惠卷向你砸来,你获得一张 " + couponBaseVo.getName();
			}
			pushBizzService.couponNotice(userIds, msg);
		}
		return ret;
	}

	@RequestMapping(value = "/exportUserPhone2Excel")
	@ResponseBody
	public Result exportUserPhone2Excel(CouponUserQuery query, HttpServletRequest request,
			HttpServletResponse response) {
		Result ret = new Result();
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "newAt"));
		int count = couponUserService.queryCount4UserNoRepeat(query);// 这里统计用户的数量【同一个用户可能获得多次优惠劵】
		SysParam sysParam = sysParamService.getByKey(SysConst.PARAM_SYS_EXPORT_TOEXCEL_MAXROWS);
		if (sysParam != null && StringUtil.isNotBlank(sysParam.getValue())) {
			int maxExportRows = Integer.valueOf(sysParam.getValue());
			if (count > maxExportRows) {
				ret.addErr("导出数量不能超过" + maxExportRows + "行!");
				return ret;
			}
		}

		List<CouponUserVo> userList = couponUserService.queryListAdmin(query, pageKit);// 不分页
		List<String> userList4Phone = Lists.newArrayList();// 电话号码列表
		if (userList != null && userList.size() > 0) {
			for (CouponUserVo couponUser : userList) {
				if (!userList4Phone.contains(couponUser.getUserIdentity())) {
					userList4Phone.add(couponUser.getUserIdentity());
				}
			}

		}
		List<Map<String, Object>> list = createExcelRecord4Phone(userList4Phone);
		String columnNames[] = {};// 列名
		String keys[] = { "userIdentity" };// map中的key
		String fileName = "用户帐号表";
		ExcelUtil.ExcelSingleOutputStream(list, keys, columnNames, fileName, request, response);
		return ret;
	}

	private List<Map<String, Object>> createExcelRecord4Phone(List<String> orderList) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "用户帐号表");
		listmap.add(map);
		for (int j = 0; j < orderList.size(); j++) {
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("userIdentity", orderList.get(j));
			listmap.add(mapValue);
		}
		return listmap;
	}
}
